import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { HttpCode } from '@/utils/Constent'
import Storage from '@/utils/Storage'
import { differentTime } from '@/utils/Auth'
import store from '@/store'

const server = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})
// 请求拦截器
server.interceptors.request.use(
  config => {
    // 判断当前token是否过期
    if (Storage.getLocal('token') && differentTime()) {
      store.dispatch('app/logout')
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject('登录过期, 请重新登录')
    }
    // 配置请求头的身份认证头部 Authorization
    config.headers.Authorization = Storage.getLocal('token')
    return config
  },
  error => Promise.reject(new Error(error))
)
// 响应拦截器
server.interceptors.response.use(
  response => {
    const { data, message, status } = response.data
    if (status === HttpCode.SUCCESS) {
      return data
    } else if (status === HttpCode.UPDATE_SUCCESS || status === HttpCode.DELETE_SUCCESS) {
      ElMessage({
        message: message,
        type: 'success'
      })
      return data
    } else if (status === HttpCode.LOGIN_FAILURE) {
      ElMessageBox.alert('登录过期，请重新登录', '登录过期提醒', {
        confirmButtonText: 'OK',
        callback: () => {
          store.dispatch('app/logout')
        }
      })
    } else {
      ElMessage({
        message: message,
        type: 'error'
      })
      return Promise.reject(message)
    }
  },
  error => Promise.reject(new Error(error))
)

export default server
